/*
* EP-Tracing System : a tool to trace mountain hike.           .kNNx
* Copyright (C) 2009  Raffaello Brondi                         'KNNNk
*                                                             ,XNNNl
* This program is free software:                             ,XNN0'
* you can redistribute it and/or modify                     ,XNNx.
* it under the terms of the                                'XNNl
* GNU General Public License                              .KNN:                     ..
* as published by                                        .0NNo                    .ONNO.
* the Free Software Foundation,                          xNNN.  :dkd,            .KNNNN;
* either version 3 of the License, or                   :NNNK ;XNNNNNo          ,KNNNX:
* (at your option) any later version.                   xNNNNcXNNNNNNk         cNNNNx.
*                                                       ,XNNNNNNNNNNX'       .xNNNK;
*                                                        .lKNNNNNNNK'       :KNNNo
*                                                          ;kNNNNNKxl;'.'l0NNNk.
* This program is distributed in                          .'  .:xXNNNNNNNNNNNO,
* the hope that it will be useful,                       :NNXd'   ,oONNNNNNk,
* but WITHOUT ANY WARRANTY;                              xNNNNN0c.    .;;,.
* without even the implied warranty of                   kNNNNNNNXd'
* MERCHANTABILITY or                                     xNNNNNNNNNNOc.
* FITNESS FOR A PARTICULAR PURPOSE.                      xNNNNNNNNNNNNXd.
* See the GNU General Public License                     ONNNN0.,o0NNNNNNl
* for more details.                                      0NNNNd    kNNNNNX.
*                                                        KNNNNl   oNNNNNXc
*                                                       .XNNNN:  dNNNNNx.
* You should have received a copy                       .XNNNN; lNNNNO'
* of the GNU General Public License                     .XNNNN; 'dxo'
* along with this program.                              .XNNNN;
* If not, see <http://www.gnu.org/licenses/>.            0NNNN:
*                                                        kNNNNc
*                                                        oNNNNd
*                                                        ;NNNN0
* Contact: rbrondi@gmail.com                             .XNNNN;
*                                                         kNNNNd
*                                                         .coo:.
*/

package EP;

import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;

/**
 *
 * @author Raffaello Brondi
 */
public class FileSystemManager {

    private static FileSystemManager fsm;

    public static FileSystemManager getInstance() {
        if (fsm == null) {
            fsm = new FileSystemManager();
        }
        return fsm;
    }
    private Object fileMutex;
    private Vector roots;
    private boolean firstWrite;
    private FileConnection file;
    private DataOutputStream out;
    private String path;

    private FileSystemManager() {
        this.fileMutex = new Object();
        this.firstWrite = true;
        this.roots = null;
        this.file = null;
        this.out = null;
        this.path = null;
    }

    public synchronized void init() {
        if (roots != null) {
            return;
        }
        Enumeration drives = FileSystemRegistry.listRoots();
        roots = new Vector();
        while (drives.hasMoreElements()) {
            roots.addElement(drives.nextElement());
        }
        return;
    }

    public synchronized Vector getRoots() {
        return this.roots;
    }

    public synchronized void setPath(String p) {
        this.path = p;
        System.out.println("path " + this.path);
    }

    public synchronized void startTrip() {
        new Thread() {

            public void run() {
                System.out.println("start thread fsm");
                synchronized (fileMutex) {
                    System.out.println("mutex acquired fsm");
                    try {
                        file = (FileConnection) Connector.open("file:///" + path, Connector.READ_WRITE);
                        if (!file.exists()) {
                            file.create();
                            System.out.println("file " + path + " created");
                        }
                        out = new DataOutputStream(file.openOutputStream(file.fileSize()));

                        byte[] buff = "{\"ps\":[".getBytes();
                        out.write(buff);
                        out.flush();
                        System.out.println("file printed");
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }.start();
    }

    public synchronized void print(final String tripContent) {
        new Thread() {

            public void run() {
                System.out.println("start thread fsm");
                synchronized (fileMutex) {
                    System.out.println("mutex acquired fsm");
                    try {
                        String value;
                        if (!firstWrite) {
                            value = "," + tripContent;
                        } else {
                            value = tripContent;
                            firstWrite = false;
                        }

                        byte[] buff = value.getBytes();
                        out.write(buff);
                        out.flush();
                        System.out.println("file printed");
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }.start();
    }

    public synchronized void endTrip(final String end) {
        new Thread() {

            public void run() {
                System.out.println("start end procedure");
                synchronized (fileMutex) {
                    try {
                        String value;
                        if (!firstWrite) {
                            value = "," + end;
                        } else {
                            value = end;
                        }
                        byte[] buff = value.getBytes();
                        out.write(buff);
                        out.flush();
                        out.close();
                        file.close();
                        System.out.println("file closed");
                        file = null;
                        firstWrite = true;
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }.start();
    }

    public synchronized void deleteTrip() {
        new Thread() {

            public void run() {
                System.out.println("delete trip");
                synchronized (fileMutex) {
                    try {
                        file.delete();
                        out.close();
                        file.close();
                        file = null;
                        firstWrite = true;
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }.start();
    }
}
